package com.work.straighttalk;

import android.media.AudioManager;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyphenate.chat.EMCallStateChangeListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.media.EMLocalSurfaceView;
import com.hyphenate.media.EMOppositeSurfaceView;
import com.work.straighttalk.presenter.VideoCallPImpl;
import com.work.straighttalk.presenter.i.VideoCallPI;
import com.work.straighttalk.ui.CallActivity;
import com.work.straighttalk.ui.i.VideoCallVI;

/**
 * Created by dllo on 16/3/14.
 */
public class VideoCallActivity extends CallActivity implements VideoCallVI, View.OnClickListener {

    private TextView callStateTextView;
    private LinearLayout comingBtnContainer;
    private Button refuseBtn;
    private Button answerBtn;
    private Button hangupBtn;
    private ImageView muteImage;
    private ImageView handsFreeImage;
    private TextView nickTextView;
    private Chronometer chronometer;
    private LinearLayout voiceContronlLayout;
    private RelativeLayout rootContainer;
    private RelativeLayout btnsContainer;
    private LinearLayout topContainer;
    private LinearLayout bottomContainer;
    private TextView monitorTextView;
    private Handler uiHandler;
    private VideoCallPI videoCallPI;

    private boolean endCallTriggerByMe = false;
    private boolean isMuteState;
    private boolean isHandsfreeState;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_call);

        uiHandler = new Handler();

        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

        callStateTextView = (TextView) findViewById(R.id.tv_call_state);
        comingBtnContainer = (LinearLayout) findViewById(R.id.ll_coming_call);
        rootContainer = (RelativeLayout) findViewById(R.id.root_layout);
        refuseBtn = (Button) findViewById(R.id.btn_refuse_call);
        answerBtn = (Button) findViewById(R.id.btn_answer_call);
        hangupBtn = (Button) findViewById(R.id.btn_hangup_call);
        muteImage = (ImageView) findViewById(R.id.iv_mute);
        handsFreeImage = (ImageView) findViewById(R.id.iv_handsfree);
        callStateTextView = (TextView) findViewById(R.id.tv_call_state);
        nickTextView = (TextView) findViewById(R.id.tv_nick);
        chronometer = (Chronometer) findViewById(R.id.chronometer);
        voiceContronlLayout = (LinearLayout) findViewById(R.id.ll_voice_control);
        btnsContainer = (RelativeLayout) findViewById(R.id.ll_btns);
        topContainer = (LinearLayout) findViewById(R.id.ll_top_container);
        bottomContainer = (LinearLayout) findViewById(R.id.ll_bottom_container);
        monitorTextView = (TextView) findViewById(R.id.tv_call_monitor);

        refuseBtn.setOnClickListener(this);
        answerBtn.setOnClickListener(this);
        hangupBtn.setOnClickListener(this);
        muteImage.setOnClickListener(this);
        handsFreeImage.setOnClickListener(this);
        rootContainer.setOnClickListener(this);


        // 设置通话人
        nickTextView.setText(username);

        // 显示本地图像的surfaceview
        localSurface = (EMLocalSurfaceView) findViewById(R.id.local_surface);
        localSurface.setZOrderMediaOverlay(true);
        localSurface.setZOrderOnTop(true);

        // 显示对方图像的surfaceview
        oppositeSurface = (EMOppositeSurfaceView) findViewById(R.id.opposite_surface);

        username = getIntent().getStringExtra("username");
        isInComingCall = getIntent().getBooleanExtra("isComingCall", false);

        videoCallPI = new VideoCallPImpl(this);
        videoCallPI.Call(username,isInComingCall);
        videoCallPI.setConversation();
    }

    @Override
    public void call() {
        soundPool = new SoundPool(1, AudioManager.STREAM_RING, 0);
//        outgoing = soundPool.load(this, R.raw.em_outgoing, 1);
        comingBtnContainer.setVisibility(View.INVISIBLE);
        hangupBtn.setVisibility(View.VISIBLE);
        String st = "正在连接对方...";
        callStateTextView.setText(st);
        EMClient.getInstance().callManager().setSurfaceView(localSurface, oppositeSurface);
        handler.sendEmptyMessage(MSG_CALL_MAKE_VIDEO);

    }

    @Override
    public void comingCall() {
        voiceContronlLayout.setVisibility(View.INVISIBLE);
        localSurface.setVisibility(View.INVISIBLE);
        Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
        audioManager.setMode(AudioManager.MODE_RINGTONE);
        audioManager.setSpeakerphoneOn(true);
        ringtone = RingtoneManager.getRingtone(this, ringUri);
        ringtone.play();
        EMClient.getInstance().callManager().setSurfaceView(localSurface, oppositeSurface);
    }

    @Override
    public void vConnectting() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                callStateTextView.setText("正在连接对方...");
            }

        });
    }

    @Override
    public void vConnected() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                callStateTextView.setText("已经和对方建立连接，等待对方接受...");
            }

        });

    }

    @Override
    public void vAccepted() {
        handler.removeCallbacks(timeoutHangup);
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                try {
                    if (soundPool != null)
                        soundPool.stop(streamID);
                } catch (Exception e) {
                }
                openSpeakerOn();
                ((TextView) findViewById(R.id.tv_is_p2p)).setText(EMClient.getInstance().callManager().isDirectCall()
                        ? "Direct" : "Relay");
                handsFreeImage.setImageResource(R.mipmap.em_icon_speaker_on);
                isHandsfreeState = true;
                chronometer.setVisibility(View.VISIBLE);
                chronometer.setBase(SystemClock.elapsedRealtime());
                // 开始记时
                chronometer.start();
                nickTextView.setVisibility(View.INVISIBLE);
                callStateTextView.setText("通话中...");
                callingState = CallingState.NORMAL;
//                startMonitor();
            }

        });

    }

    @Override
    public void vDisconnnected(EMCallStateChangeListener.CallError callError) {
        handler.removeCallbacks(timeoutHangup);
        final EMCallStateChangeListener.CallError fError = callError;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

            }
            private void postDelayedCloseMsg() {
                uiHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        saveCallRecord();
                        Animation animation = new AlphaAnimation(1.0f, 0.0f);
                        animation.setDuration(800);
                        rootContainer.startAnimation(animation);
                        finish();
                    }
                }, 200);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_refuse_call: // 拒绝接听
                refuseBtn.setEnabled(false);
                handler.sendEmptyMessage(MSG_CALL_REJECT);
                break;
            case R.id.btn_answer_call: // 接听电话
                answerBtn.setEnabled(false);
                openSpeakerOn();
                if (ringtone != null)
                    ringtone.stop();

                callStateTextView.setText("正在接听...");
                handler.sendEmptyMessage(MSG_CALL_ANSWER);
                handsFreeImage.setImageResource(R.mipmap.em_icon_speaker_on);
                isAnswered = true;

                comingBtnContainer.setVisibility(View.INVISIBLE);
                hangupBtn.setVisibility(View.VISIBLE);
                voiceContronlLayout.setVisibility(View.VISIBLE);
                localSurface.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_hangup_call: // 挂断电话
                hangupBtn.setEnabled(false);
                chronometer.stop();
                endCallTriggerByMe = true;
                callStateTextView.setText("正在挂断..");
                handler.sendEmptyMessage(MSG_CALL_END);
                break;
            case R.id.iv_mute: // 静音开关
                if (isMuteState) {
                    // 关闭静音
                    muteImage.setImageResource(R.mipmap.em_icon_mute_normal);
                    audioManager.setMicrophoneMute(false);
                    isMuteState = false;
                } else {
                    // 打开静音
                    muteImage.setImageResource(R.mipmap.em_icon_mute_on);
                    audioManager.setMicrophoneMute(true);
                    isMuteState = true;
                }
                break;
            case R.id.iv_handsfree: // 免提开关
                if (isHandsfreeState) {
                    // 关闭免提
                    handsFreeImage.setImageResource(R.mipmap.em_icon_speaker_normal);
                    closeSpeakerOn();
                    isHandsfreeState = false;
                } else {
                    handsFreeImage.setImageResource(R.mipmap.em_icon_speaker_on);
                    openSpeakerOn();
                    isHandsfreeState = true;
                }
                break;
            case R.id.root_layout:
                if (callingState == CallingState.NORMAL) {
                    if (bottomContainer.getVisibility() == View.VISIBLE) {
                        bottomContainer.setVisibility(View.GONE);
                        topContainer.setVisibility(View.GONE);
                    } else {
                        bottomContainer.setVisibility(View.VISIBLE);
                        topContainer.setVisibility(View.VISIBLE);
                    }
                }
                break;
            default:
                break;
        }

    }

    @Override
    protected void onDestroy() {
        localSurface = null;
        oppositeSurface = null;
        videoCallPI.onDestroy();
        super.onDestroy();
    }
}
